# ###########上传图片#############
# from fdfs_client.client import Fdfs_client
#
# # 1.创建客户端
# # 修改加载配置文件的路径
# client = Fdfs_client('utils/fastdfs/client.conf')
#
# # 2.上传图片
# # 文件的绝对路径
# client.upload_by_filename('D:/Downloads/data/00/00/CtM3BVni0w6AUaJbAAAmv27pX4k0365964')
"""
{'Group name': 'group1', 'Remote file_id': 'group1\\M00/00/00/rBIAA2arStyAV2HtAAAmv27pX4k6176797', 'Status': 'Upload successed.', 'Local file name': 'D:/Downloads/data/00/00/CtM3BVni0w6AUaJbAAAmv27pX4k0365964', 'Uploaded size': '9.00KB', 'Storage IP': '192.168.89.75'}
"""
# 3.获取file_id   upload_by_filename上传成功后会返回字典数据
# 字典数据中有file_id

import json

from django.shortcuts import render
from django.views import View
from django.http import JsonResponse

from utils.goods import get_categories, get_breadcrumb
from apps.contents.models import ContentCategory
from apps.goods.models import GoodsCategory, SKU


class IndexView(View):

    def get(self, request):
        """
        首页数据两部分
        1.商品分类数据 2.广告数据
        """
        # 1.商品分类数据
        categories = get_categories()
        # 2.广告数据
        contents = {}
        content_categories = ContentCategory.objects.all()
        for cat in content_categories:
            contents[cat.key] = cat.content_set.filter(status=True).order_by('sequence')

        context = {
            'categories': categories,
            'contents': contents,
        }

        # 将数据传递给模板
        return render(request, 'index.html', context)


class ListView(View):

    def get(self, request, category_id):
        # 1.接受参数
        # 排序字段
        ordering = request.GET.get('ordering')
        # 每页的数据
        page_size = request.GET.get('page_size')
        # 需要的第几页的数据
        page = request.GET.get('page')
        # 2.获取分类id
        # 3.根据分类id进行分类数据查询
        try:
            category = GoodsCategory.objects.get(id=category_id)
        except GoodsCategory.DoesNotExist:
            return JsonResponse({'code': 400, 'errmsg': '参数缺失'})
        # 4.获取面包屑数据
        breadcrumb = get_breadcrumb(category)
        # 5.根据分类查询对应的sku数据，然后排序、分页
        skus = SKU.objects.filter(category=category, is_launched=True).order_by(ordering)
        # 分页
        from django.core.paginator import Paginator
        paginator = Paginator(skus, per_page=page_size)
        # 获取指定页码的数据
        page_skus = paginator.page(page)
        sku_list = []
        # 将对象转换为字典数据
        for sku in page_skus.object_list:
            sku_list.append({
                'id': sku.id,
                'name': sku.name,
                'default_image_url': sku.default_image.url,
                'price': sku.price
            })
        # 获取总页码
        total_num = paginator.num_pages

        return JsonResponse({
            'code': 0,
            'errmsg': 'ok',
            'breadcrumb': breadcrumb,
            'list': sku_list,
            'count': total_num
        })


class HotGoodsView(View):

    def get(self, request, category_id):
        # 1.获取数据，根据分类id获取数据
        skus = SKU.objects.filter(category_id=category_id, is_launched=True).order_by('-sales')[:3]
        # 2.转换为字典数据
        hot_skus = []
        for sku in skus:
            hot_skus.append({
                'id': sku.id,
                'default_image_url': sku.default_image.url,
                'name': sku.name,
                'price': sku.price
            })
        return JsonResponse({'code': 0, 'errmsg': 'ok', 'hot_skus': hot_skus})


from haystack.views import SearchView


class MySearchView(SearchView):

    def create_response(self):
        # 获取搜索的结果
        context = self.get_context()
        sku_list = []
        for sku in context['page'].object_list:
            sku_list.append({
                'id': sku.object.id,
                'name': sku.object.name,
                'price': sku.object.price,
                'default_image_url': sku.object.default_image.url,
                'searchkey': context.get('query'),
                'page_size': context['page'].paginator.num_pages,
                'count': context['page'].paginator.count
            })

        return JsonResponse(sku_list, safe=False)


from utils.goods import get_categories
from utils.goods import get_breadcrumb
from utils.goods import get_goods_specs


class DetailView(View):

    def get(self, request, sku_id):
        try:
            sku = SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            pass
        # 1.分类数据
        categories = get_categories()
        # 2.获取面包屑数据
        breadcrumb = get_breadcrumb(sku.category)
        # 3.SKU信息
        # 4.规格信息
        goods_specs = get_goods_specs(sku)

        context = {
            'categories': categories,
            'breascrumb': breadcrumb,
            'sku': sku,
            'specs': goods_specs,
        }
        return render(request, 'detail.html', context)


class DetailVisitView(View):

    def post(self, request, category_id):
        # 1.获取分类
        try:
            category = GoodsCategory.objects.get(id=category_id)
        except Exception:
            return JsonResponse({'code': 400, 'errmsg': '参数缺失'})
        # 2.获取日期信息
        from datetime import date
        today_date = date.today()

        from apps.goods.models import GoodsVisitCount

        try:
            date_count = GoodsVisitCount.objects.get(date=today_date)
        except:
            date_count = GoodsVisitCount()
        try:
            date_count.count += 1
            date_count.category = category
            date_count.date = today_date
            date_count.save()
        except Exception:
            return JsonResponse({'code': 400, 'errmsg': '新增失败'})

        return JsonResponse({'code': 0, 'errmsg': 'ok'})


class UserBrowseHistory(View):

    def post(self, request):
        # 1.获取数据
        json_dict = json.loads(request.body)
        sku_id = json_dict.get('sku_id')
        # 2.校验参数
        try:
            SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return JsonResponse({'code': 400, 'errmsg': 'sku不存在'})
        # 3.连接redis，保存浏览数据
        from django_redis import get_redis_connection
        redis_cli = get_redis_connection('history')
        pl = redis_cli.pipeline()
        user_id = request.user.id

        # 去重
        pl.lrem('history_%s' % user_id, 0, sku_id)
        # 存储
        pl.lpush('history_%s' % user_id, sku_id)
        # 截取列表，只留5个
        pl.ltrim('history_%s' % user_id, 0, 4)

        pl.execute()

        return JsonResponse({'code': 0, 'errmsg': 'ok'})

    def get(self, request):
        # 连接redis,获取记录的sku_id
        from django_redis import get_redis_connection
        redis_cli = get_redis_connection('history')
        sku_ids = redis_cli.lrange('history_%s' % request.user.id, 0, -1)

        # 根据sku_ids数据返回列表数据
        sku_list = []
        for sku_id in sku_ids:
            sku = SKU.objects.get(id=sku_id)
            sku_list.append({
                'id': sku.id,
                'name': sku.name,
                'default_image_url': sku.default_image.url,
                'price': sku.price
            })

            return JsonResponse({'code': 0, 'errmsg': 'ok', 'skus': sku_list})
